package com.example.network.service.impl;

import com.example.network.Util.TokenUtils;
import com.example.network.controller.dto.LoginDTO;
import com.example.network.controller.request.FileRequest;
import com.example.network.controller.request.LoginRequest;
import com.example.network.exception.ServiceException;
import com.example.network.mapper.AdminMapper;
import com.example.network.model.entity.Admin;
import com.example.network.model.entity.TimeTable;
import com.example.network.service.AdminService;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LR
 */
@Slf4j
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    private static final String PASS_SALT = "yang";

    @Resource
    private AdminMapper adminMapper;

    /**
     * 通过username查询单条数据
     */
    @Override
    public List<TimeTable> selectByEmail(String email) {
        List<TimeTable> timeTable = adminMapper.selectByEmail(email);
        if (timeTable.isEmpty()){
            throw new ServiceException("没有这个用户，请确认用户名是否正确");
        }
        return timeTable;
    }

    /**
     * 用户登录
     *
     * @param request
     * @return
     */
    @SneakyThrows
    @Override
    public LoginDTO login(LoginRequest request) {
        Admin admin1 = null;
        try {
            admin1 = adminMapper.getByUserName(request.getEmail());
        }catch (Exception e){
            throw new ServiceException("用户名出错");
        }
        if (admin1 == null){
            throw new ServiceException("管理员用户名不存在");
        }
        if (!request.getPassword().equals(admin1.getPassword())){
            throw new ServiceException("密码错误，请重新输入！");
        }
        LoginDTO loginDTO = new LoginDTO();

        String token = TokenUtils.genToken(request.getEmail(),request.getPassword());
        loginDTO.setToken(token);
        BeanUtils.copyProperties(admin1, loginDTO);
        return loginDTO;
    }



    @Override
    public List<TimeTable> selectOneByAll() {
        return adminMapper.selectOneByAll();
    }

    @Override
    public List<FileRequest> selectAllFile() {
        return adminMapper.selectAllFile();
    }


}


